/*!
 * Created by 李远明 on 2017-04-14 21:48.
 */
define(["jquery", "validate", "serializeJSON", "jsencrypt", "Util"], function($) {

    var JSEncrypt = require("jsencrypt").JSEncrypt;
    var Util = require("Util");

    /**
     * 加密密码
     * @param pwd
     */
    function getEncryptPwd(pwd) {
        var pubKey = $("#pubKey").val();
        if (!pwd || !pubKey) {
            return pwd;
        }
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(pubKey);
        return encrypt.encrypt(pwd);
    }

    //注册验证
    $.validator.setDefaults({
        errorElement: "em",
        errorClass: "valid-error",

        highlight: function(element) {
            $(element).closest(".form-group").addClass("has-error");
        },
        success: function(label) {
            label.closest(".form-group").removeClass("has-error");
            label.remove();
        },
        errorPlacement: function(error, element) {
            element.parent("div").append(error);
        }
    });

    var form = $("#form_login");
    return {
        init: init
    };

    function init() {
        console.log("login init");
        validate();
        formSubmit();
    }

    function validate() {
        form.validate({
            rules: {
                username: {
                    required: true
                },
                password: {
                    required: true
                },
                captchaCode: {
                    required: true
                }
            },
            messages: {
                username: {
                    required: '请输入用户名'
                },
                password: {
                    required: '请输入登录密码'
                },
                captchaCode: {
                    required: '请输入验证码'
                }
            },
            //提交
            submitHandler: function(form) {
                form.submit();
            }
        });
    }

    function formSubmit() {
        form.submit(function(e) {
            e.preventDefault();
            if (!form.valid()) {
                return false;
            }
            var data = form.serializeJSON();
            data.password = getEncryptPwd(data.password);
            $.ajax("passport/login?_=" + Date.now(), {
                type: 'POST',
                dataType: 'JSON',
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                data: data
            }).done(function(result, statusText, jqXhr) {
                if (result.code === '000000') {
                    Util.Cookie.setALCookie();
                    var retUrl = Util.getURLParameter('destUrl');
                    window.location.href = retUrl || "index.html";
                } else { // 登录失败
                    showError(result.message, "error", ["#loginName"]);
                    refreshCaptcha(result.data.showCaptcha, 'div-captchaCode', 'img-captchaCode');
                }
            }).fail(function(jqXhr, statusText, errorThrown) { // 网络超时，请稍后再试
                console.log(jqXhr.status);
                console.log(jqXhr.readyState);
                console.log(statusText);
            }).always(function(jqXhr, statusText, errorThrown) { // complete
                //this; // 调用本次AJAX请求时传递的options参数
            });
        });
    }

    function checkPwd() {
        strengthBar(
            $("#passwordStrength"),
            $("#passwordStrengthText"),
            $("#passwordRow"),
            $("#J_password"),
            $("#pws-title"),
            {
                tooShort: "太短",
                veryWeak: "非常弱",
                weak: "弱",
                good: "良好",
                strong: "强",
            });
    }
});
